var tabTitle = document.getElementById("tabTitle");
var typeDiv = document.getElementById("typeDiv");
var acreDiv = document.getElementById("acreDiv");
var rentDiv = document.getElementById("rentDiv");
var acreageDiv = document.getElementById("acreageDiv");
var backDrop = document.getElementById("backDrop");
var titel = document.getElementById("title");
var marginTopDiv = document.getElementById("marginTopDiv");
var token;
var typeList;
var areaList;
var rentList;
var acreageList;
var buildTypeId ;
var buildId = "12";

var typeFilter = "";
var acreFilter = "";
var rentFilter = "";
var acreageFilter = "";
var filterStr = "";

var pageNum = 1;
var itemNum = 20;
var pageflag = "";
var keyword = "";
var titleText = "";
var titleOther = document.getElementById("titleOther");
var filterDiv = document.getElementById("filterDiv");
var scDiv = document.getElementById("scDiv");

(function($) {
	setPxPerRem();
	mui.plusReady(function() {
		pageflag = getQueryString("pageflag");
		keyword = getQueryString("keyword");
		buildId = getQueryString("buildId");
		titleText = getQueryString("titleText");
		
		if (!isEmpty(titleText)) {
			titleOther.innerHTML = titleText;
			showEle(marginTopDiv);
		}
		
		var clientWidth = getQueryString("clientWidth");
		token = localStorage.getItem("token_type") + " " + localStorage.getItem("access_token");
		setPxPerRem(clientWidth);
		if(pageflag.indexOf("page_main") > -1) {
			if(isHaveNet()) {
				getTitleType();
			} else {
				mui.toast("无网络连接！")
			}
		} else if(pageflag.indexOf("search") > -1) {
			document.getElementById("keyword").innerHTML = keyword;
			hiddenEle(document.getElementById("scDiv"));
			showEle(filterDiv);
			if(isHaveNet()) {
				getTitleType();
			} else {
				mui.toast("无网络连接！")
			}
		} else {
			hiddenEle(filterDiv);
			showEle(document.getElementById("scDiv"));
			document.getElementById("herderDiv").style.height = "50px";
		}

	});
})(mui);

mui.init({
	pullRefresh: {
		container: '#pullrefresh',
		down: {
			style: 'circle',
			callback: pulldownRefresh
		},
		up: {
			auto: true,
			contentrefresh: '正在加载...',
			callback: pullupRefresh
		}
	}
});

var searchInput = document.getElementById("searchInput");
if(searchInput) {
	searchInput.addEventListener('click', function() {
		var wv = plus.webview.currentWebview();
		wv.close("pop-out");
	}, false);
}

/**
 * 下拉刷新业务实现
 */
var isRefresh = false;
var countNum = 0;

function pulldownRefresh() {
	pageNum = 1;
	isRefresh = true;
	removeLi("resoutcesList");
	filterStr = typeFilter + ',' + acreFilter + ',' + rentFilter + ',' + acreageFilter;
	if(isHaveNet()) {
		console.log("pageflag==>>" + pageflag);
		if(pageflag.indexOf("page_main") > -1) {
			getResourcesList(buildId , filterStr);
		} else if(pageflag.indexOf("search") > -1) {
			getResourcesList(buildId , filterStr, keyword);
		} else {
			getFavoriteBuild();
		}
	} else {
		mui.toast("无网络连接！")
	}

}

function clearnAndLoad(buildId1 , filterStr){
	pageNum = 1;
	isRefresh = true;
	buildId = buildId1 ;
	removeLi("resoutcesList");
	if(isHaveNet()) {
		getResourcesList(buildId , filterStr);
	} else {
		mui.toast("无网络连接！")
	}
}
/**
 * 上拉加载
 */
var isLoad = false;

function pullupRefresh() {
	isLoad = true;
	console.log("pageflag==>>" + pageflag);
	filterStr = typeFilter + ',' + acreFilter + ',' + rentFilter + ',' + acreageFilter;
	if(pageflag.indexOf("page_main") > -1) {
		getResourcesList(buildId ,filterStr);
	} else if(pageflag.indexOf("search") > -1) {
		getResourcesList(buildId ,filterStr, keyword);
	} else {
		getFavoriteBuild();
	}
}

var typeFlag = false;
var acreFlag = false;
var rentFlag = false;
var acreageFlag = false;

mui("#tabTitle").on('click', ".title-type", function() {
	hiddenPopupwindow(typeDiv);
	hiddenPopupwindow(acreDiv);
	hiddenPopupwindow(rentDiv);
	hiddenPopupwindow(acreageDiv);
	changeTextandIcon(tabTitle, "title-active", "../../ui/building/images/04zaijian/06down_black.png", this);
	var icon = this.getElementsByTagName("img")[0];

	if(this.classList.contains("title-active")) {
		if(icon.src.indexOf("03upicon") > -1) {
			icon.src = "../../ui/building/images/04zaijian/04down.png"
			return;
		} else {
			icon.src = "../../ui/building/images/04zaijian/03upicon.png"
		}
	} else {
		addClass('title-active', this);
		icon.src = "../../ui/building/images/04zaijian/03upicon.png"
	}
	if(this.id == "type") {
		if(!typeFlag) {
			var inseter = document.getElementById("insertType");
			createItem(typeList, inseter);
			typeFlag = true;
		}
		showPopupwindow(typeDiv);
	} else if(this.id == "area") {

		if(!acreFlag) {
			var inseter = document.getElementById("insertAcre");
			createItem(areaList, inseter);
			acreFlag = true;
		}
		showPopupwindow(acreDiv);
	} else if(this.id == "rent") {
		if(!rentFlag) {
			var inseter = document.getElementById("insertRent");
			createItem(rentList, inseter);
			rentFlag = true;
		}
		showPopupwindow(rentDiv);
	} else if(this.id == "acreage") {
		if(!acreageFlag) {
			var inseter = document.getElementById("insertAcreage");
			createItem(acreageList, inseter);
			acreageFlag = true;
		}
		showPopupwindow(acreageDiv);
	}
});

function changeTextandIcon(parentNode, className, imgPath, ele) {
	var activeTab = parentNode.getElementsByClassName(className)[0];
	if(ele.id == activeTab.id) {
		return;
	}
	deleteClass(className, activeTab);
	activeTab.getElementsByTagName("img")[0].src = imgPath;
}

function changeTextandIcon1(parentNode, className) {
	var activeTab = parentNode.getElementsByClassName(className)[0];
	deleteClass(className, activeTab);
	hiddenEle(activeTab.getElementsByTagName("img")[0]);
}

function createItem(arr, insertDiv) {

	if(isEmpty(arr)) {
		return;
	}

	for(var i = 0; i <= arr.length; i++) {
		var createLi = document.createElement('li');

		if(i == 0) {
			createLi.id = "";
			createLi.className = "mui-table-view-cell item-active";
			createLi.innerHTML = '<span>全部</span><img class="" src="../../ui/building/images/04zaijian/04.png"/>';
		} else {
			createLi.id = arr[i - 1].id;
			createLi.className = "mui-table-view-cell";
			createLi.innerHTML = '<span>' + arr[i - 1].name + '</span><img class="mui-hidden" src="../../ui/building/images/04zaijian/04.png"/>';
		}
		document.body.appendChild(createLi);
		insertBefore(createLi, insertDiv);
	}

//	mui("#typeDiv").on('click', "li", function() {
//		typeFilter = this.id;
//		buildTypeId = this.id;
//		itemClick(this, typeDiv, "typeImg");
//	});
//
//	mui("#acreDiv").on('click', "li", function() {
//		acreFilter = this.id;
//		itemClick(this, acreDiv, "acreImg");
//	});

	mui("#rentDiv").on('click', "li", function() {
		rentFilter = this.id;
		itemClick(this, rentDiv, "rentImg" , "rentEm");
	});

	mui("#acreageDiv").on('click', "li", function() {
		acreageFilter = this.id;
		itemClick(this, acreageDiv, "acreageImg" , "acreageEm")
	});

}

function itemClick(ele, clickDiv, imgID , emID) {
	if(ele.classList.contains("item-active")) {
		hiddenPopupwindow(clickDiv);
		return;
	}
	changeTextandIcon1(clickDiv, "item-active");
	addClass("item-active", ele);
	showEle(ele.getElementsByTagName("img")[0]);
	document.getElementById(imgID).src = "../../ui/building/images/04zaijian/04down.png"
	document.getElementById(emID).innerHTML = ele.getElementsByTagName("span")[0].innerHTML;
	hiddenPopupwindow(clickDiv);
	plus.nativeUI.showWaiting();
	pulldownRefresh();
}

function hiddenPopupwindow(filterDiv) {
	hiddenEle(filterDiv);
	hiddenEle(backDrop);
}

function showPopupwindow(filterDiv) {
	addClass('show-div', filterDiv);
	showEle(filterDiv);
	showEle(backDrop);
}

backDrop.addEventListener('click', function() {
	hiddenPopupwindow(typeDiv);
	hiddenPopupwindow(acreDiv);
	hiddenPopupwindow(rentDiv);
	hiddenPopupwindow(acreageDiv);
	var activeTab = tabTitle.getElementsByClassName("title-active")[0];
	activeTab.getElementsByTagName('img')[0].src = "../../ui/building/images/04zaijian/04down.png"
}, false);

var typeSpans;

/**
 * 获取标题头类型
 */
function getTitleType() {
	typeSpans = document.getElementById("tabTitle").getElementsByTagName('span');
	var jsonData = {};

	plus.nativeUI.showWaiting();

	var opts = {
		url: '/building/attribute',
		addressUrl: "testline",
		requestType: "GET",
		pastDate: jsonData
	};

	crossDomainAjax(opts, function(data) {

		if(!isEmpty(data)) {
			toastMesg(data.meta, 10000, 20000);
			var rows = data.data;

			if(!isEmpty(rows) && rows.length > 0) {

				console.log(typeSpans.length + "-----");
				var length = 0;
				if(rows.length > typeSpans.length) {
					length = rows.length;
				} else {
					length = typeSpans.length;
				}

				for(var i = 0; i < length; i++) {
					var row = rows[i];
					var spanTab = typeSpans[i];
					if(!isEmpty(row)) {
						if(i == 0) {
							rentList = row.values;
						} else if(i == 1) {
							acreageList = row.values;
						}
//						else if(i == 2) {
//							rentList = row.values;
//						} else if(i == 3) {
//							acreageList = row.values;
//						}
					}
					spanTab.innerHTML = row.name;
				}
			} else {
				//				mui.toast("没有数据");
			}
		} else {
			mui.toast("请求失败");
		}

	});
}

function getResourcesList(buildId , filter , keywords) {
	var jsonData;
	var urlStr = "/building";
	if(!isEmpty(keywords)) {
		jsonData = {
			building_attribute_value_id: filter,
			page: pageNum,
			per_page: itemNum,
			keywords: keywords
		}
		urlStr = "/search/building";
	} else if(!isEmpty(buildId)){
		jsonData = {
			building_attribute_value_id: filter,
			building_category_id: buildId,		
			page: pageNum,
			per_page: itemNum
		}
		urlStr = "/building";
	} else {
		jsonData = {
			building_attribute_value_id: filter,
			page: pageNum,
			per_page: itemNum
		}
		urlStr = "/building";
	}
	checkParams(jsonData);
	logText(jsonData);
	var opts = {
		url: urlStr,
		addressUrl: "testline",
		requestType: "GET",
		pastDate: jsonData
	};
	crossDomainAjax(opts, function(data) {
		plus.nativeUI.closeWaiting();
		if(!isEmpty(data)) {
			if(isEmpty(data.data)) {
				//				mui.toast("暂无数据");
				return;
			}

			for(var i = 0; i < data.data.length; i++) {
				createIndexItem(data.data[i]);
			}
		}
		var meta = data.meta;
		if(!isEmpty(meta)) {
			if(meta.code && isEmpty(meta.mesg)) {
				mui.toast(meta.mesg);
			}
			if(meta.pagination) {
				var pageCount = meta.pagination.total_pages;
				if(!isEmpty(pageCount)) {
					countNum = parseInt(pageCount);
				}
			}

		}
		if(isRefresh) {
			mui('#pullrefresh').pullRefresh().endPulldown();
			isRefresh = false;
		}

		if(isLoad) {
			isLoad = false;
			mui('#pullrefresh').pullRefresh().endPullup((pageNum > countNum));
		}
		if(pageNum == 1) {
			//			showEle(content);
		}
		pageNum++;

		mui("#resoutcesList").on('click', 'li', function() {
			var id = this.id;
			var postData = {
				pageFlag: 'page_resources.html',
				itemID: id
			}

			var chang = {
				pageUrl: 'page_buildinfo.html',
				postData: postData,
				aniShow: "fade-in"
			}
			pageChange(chang);
		});

	});
}

function createIndexItem(row) {
	var createLi = document.createElement('li');
	createLi.id = row.id;
	var acreageStr = '';

	if(!isEmpty(row.investment_acreage)) {
		acreageStr = '<p class="left">招商面积：<span>' + row.investment_acreage + '</span></p>'
	} else {
		acreageStr = '<p class="left">建筑面积：<span>' + row.covered_acreage + '</span></p>'
	}
	var startStr = '';
	if(!isEmpty(row.is_hot) && 1 == row.is_hot) {
		startStr = '<img class="star" src="../../ui/building/images/04zaijian/01.png" />';
	} else {
		startStr = "";
	}

	var vacancy = (100.00 - row.vacancy_rate).toFixed(3);

	if(isEmpty(row.thumb)) {
		row.thumb = "../../ui/building/images/04zaijian/06.jpg";
	}

	createLi.innerHTML = startStr + '<div class="left-img">' +
		'<img src="' + row.thumb + '" />' +
		'</div>' +
		'<div class="right_content">' +
		'<p class="item-title">' + row.name + '</p>' +
		'<div class="address">' +
		'<img class="position-icon" src="../../ui/building/images/04zaijian/05.png" />' +
		'<span id="address" class="item-address">' + row.address + '</span>' +
		'</div>' +
		'<div class="item-info">' + acreageStr +
		'<p class="right">空闲面积：<span>' + vacancy + '%</span></p>' +
		'</div>' +
		'</div>' +
		'<div class="line-1px"></div>';

	document.body.appendChild(createLi);
	insertBefore(createLi, insertDiv);
}

function getFavoriteBuild() {
	var urlStr = getRequestAddressUrl("testline") + "/user/favorite/building";
	console.log("token==>>" + token);
	var settings = {
		url: urlStr,
		method: "GET",
		data: {
			"page": pageNum,
			"per_page": itemNum
		},
		headers: {
			"accept": "application/json",
			"authorization": token
		}
	}

	$.ajax(settings).done(function(data) {
		plus.nativeUI.closeWaiting();
		if(!isEmpty(data)) {
			var rows = data.data;
			if(!isEmpty(rows)) {
				for(var i = 0; i < rows.length; i++) {
					createIndexItem(rows[i]);
				}
			}
		}
		var meta = data.meta;
		if(!isEmpty(meta)) {
			if(meta.code && isEmpty(meta.mesg)) {
				mui.toast(meta.mesg);
			}
			if(meta.pagination) {
				var pageCount = meta.pagination.total_pages;
				if(!isEmpty(pageCount)) {
					countNum = parseInt(pageCount);
				}
			}

		}
		console.log("isRefresh==>>" + isRefresh);
		console.log("isLoad==>>" + isLoad);
		if(isRefresh) {
			mui('#pullrefresh').pullRefresh().endPulldown();
			isRefresh = false;
		}
		if(isLoad) {
			isLoad = false;
			mui('#pullrefresh').pullRefresh().endPullup((pageNum > countNum));
		}
		pageNum++;

		mui("#resoutcesList").on('click', 'li', function() {
			var id = this.id;
			var postData = {
				pageFlag: 'page_search_result.html',
				itemID: id
			}

			var chang = {
				pageUrl: 'page_buildinfo.html',
				postData: postData,
				aniShow: "fade-in"
			}
			pageChange(chang);
		});
		
	});
}

document.getElementById("positionDiv").addEventListener('click', function() {
	var postData = {
		pageflag: "main.html"
	}

	var pageChange1 = {
		pageUrl: "page_searchAddress.html",
		postData: postData,
		aniShow: "fade-in"
	}
	pageChange(pageChange1);
}, false);
